package org.duang.db.sql;

import org.duang.db.IdEntity;
import org.duang.db.sql.parser.SqlEncodeConvetor;
import org.duang.kit.ClassKit;
import org.duang.kit.SqlKit;
import org.duang.kit.ToolsKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public  abstract class SqlBaseDao<T> implements ISqlDao<T> {
	
	private final static Logger logger = LoggerFactory.getLogger(SqlBaseDao.class);
	
	protected Class<T> cls;
	
	public SqlBaseDao() {
		
	}
	
	public SqlBaseDao(final Class<T> cls){
		init(cls);
	}
	
	public void init(final Class<T> cls){
		boolean isExtends = ClassKit.isExtends(cls, IdEntity.class.getCanonicalName());
		if(!isExtends){
			throw new RuntimeException("the "+cls.getCanonicalName()+" is not extends "+ IdEntity.class.getCanonicalName() +", exit...");
		}
		this.cls = cls;
		//auto create talbe and index run at event		
		try {
			SqlKit.createTable(cls);
			SqlKit.createIndex(cls);
		} catch (Exception e) {
			logger.warn("init "+cls.getName()+" table fail: " + e.getMessage(), e);
		}		
//		new SqlListener().onEvent(new SqlEvent(cls));		
	}

	/**
	 * 持久化到数据库, 会自己根据entity是否有id值进行保存或更新操作
	 * @param entity	需要持久化的对象
	 * @return			正确持久化到数据库返回true, 否则执行出异常
	 */
	@Override
	public boolean save(T entity) throws Exception {
		SqlObject sqlObj = SqlEncodeConvetor.convetor(cls, entity);
		int isok = DBSession.execute(sqlObj.getSql(), sqlObj.getParams().toArray());		
		IdEntity vo = (IdEntity)entity;		
		if(ToolsKit.isEmpty(vo.getId())) {
			String id = (String)sqlObj.getParams().get(sqlObj.getParams().size()-1);
			vo.setId(id); //ToolsKit.getObjectIdByThread()
		}
		return ( isok == 1)? true : false;
	}
	
	/**
	 * 新增数据
	 * @param entity
	 * @return
	 * @throws Exception
	 */
	public boolean insert(T entity) throws Exception {
		SqlObject sqlObj = SqlEncodeConvetor.convetorIdentity(entity, true);
		int isok = DBSession.execute(sqlObj.getSql(), sqlObj.getParams().toArray());		
		IdEntity vo = (IdEntity)entity;		
		if(ToolsKit.isEmpty(vo.getId())) {
			String id = (String)sqlObj.getParams().get(sqlObj.getParams().size()-1);
			vo.setId(id); //ToolsKit.getObjectIdByThread()
		}
		return ( isok == 1)? true : false;
	}
	
//	/**
//	 * 持久化到数据库，新增一条记录
//	 * @param entity
//	 * @return
//	 * @throws Exception
//	 */
//	public boolean insert( T entity) throws Exception {
//		IdEntity idEntity = (IdEntity)entity;
//		String id = idEntity.getId();
//		idEntity.setId("");
//		SqlObject sqlObj = SqlEncodeConvetor.convetor(cls, entity);
//		List<Object> params = sqlObj.getParams();
//		params.remove(params.size()-1); params.add(id);
//		int isok = DBSession.execute(sqlObj.getSql(),params.toArray());
//		return ( isok == 1)? true : false;
//	}
	/*
	@Override
	public WriteResult update(Query query, Update update) throws Exception {
		SqlEncodeConvetor.convetor(cls, query);
		SqlEncodeConvetor.convetor(cls, update);
//		DBSession.execute(sql, params)
		return null;
	}

	@Override
	public T findOne(Query query) throws Exception {
		SqlObject sqlObj = SqlEncodeConvetor.convetor(cls, query);		
		List<Map<String,Object>> results = DBSession.query(sqlObj.getSql(), sqlObj.getParams().toArray());
		if(ToolsKit.isEmpty(results)) return null;
		return SqlKit.toBean(cls, results.get(0));
	}

	@Override
	public List<T> findList(Query query) throws Exception {
		SqlObject sqlObj = SqlEncodeConvetor.convetor(cls, query);
		List<Map<String,Object>> results = DBSession.query(sqlObj.getSql(), sqlObj.getParams().toArray());
		if(ToolsKit.isEmpty(results)) return null;
		return SqlKit.toBeans(cls, results);
	}
	*/
	public SqlHelper<T> duang() {
		return  new SqlHelper<T>(cls);
	}

}
